package com.atguigu.tingshu.search.runners;

import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.search.service.impl.ItemServiceImpl;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <a href="https://www.shallowrecall.top/">Recall`Blog</a></br>
 * <a href="https://github.com/ShallowRecall">GitHub</a>
 *
 * @author Recall
 * @createTime 2025/03/26 17:56
 **/
//@Component
public class BloomFilterRunners implements ApplicationRunner, CommandLineRunner, ApplicationContextAware {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    private ApplicationContext applicationContext;

    /**
     * run方法在spring容器启动完毕的时候调到
     *
     * ApplicationArguments：回调时候的参数。
     * --：可选参数
     * 不加-- 必选参数
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 1.从spring容器中获取到布隆过滤器的Bean对象
        RBloomFilter rBloomFilter = applicationContext.getBean("rBloomFilter", RBloomFilter.class);

        // 2.从spring容器中获取应用的Bean对象
        ItemServiceImpl itemServiceImpl = applicationContext.getBean("itemServiceImpl", ItemServiceImpl.class);

        // 3.获取数据
        List<Long> albumInfoIdList = itemServiceImpl.getAlbumInfoIdList();

        // 4.将数据放到布隆过滤器中
        albumInfoIdList.stream().forEach(rBloomFilter::add);

        // 5.布隆过滤器元素是否同步进去
        logger.info("布隆过滤器初始化成功,且布隆中的元素个数为：{}", rBloomFilter.count());
    }

    @Override
    public void run(String... args) throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
